package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustomException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmMaterialDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsAndMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * @author shiminghui
 * @date 2024/11/1 16:04
 * @description: TODO
 */
@Service
@Slf4j
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {
    @Autowired
    private FileStorageService fileStorageService;
    @Autowired
    private WmNewsAndMaterialMapper wmNewsAndMaterialMapper;

    /**
     * 图片上传
     *
     * @param multipartFile
     * @param wmUser
     * @return
     */
    @Override
    public ResponseResult uploadPicture(MultipartFile multipartFile, WmUser wmUser) {

        //检查参数
        if (multipartFile == null || multipartFile.isEmpty()) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //1.上传图片到minio
        String filename = UUID.randomUUID().toString().replace("-", "");
        String postfix = multipartFile.getOriginalFilename().substring(multipartFile.getOriginalFilename().lastIndexOf("."));
        String url;
        try {
            url = fileStorageService.uploadImgFile("", filename + postfix, multipartFile.getInputStream());
            log.info("上传图片到minio成功，url:{}", url);
        } catch (IOException e) {
            log.error(e.getMessage(), e);
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "上传文件失败");// 上传失败
        }

        //2.保存图片信息到mysql
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setUserId(wmUser.getId());
        wmMaterial.setType((short) 0);
        wmMaterial.setUrl(url);
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setCreatedTime(new Date());
        save(wmMaterial);

        //3.返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 图片列表展示
     *
     * @param wmMaterialDto
     * @param user
     * @return
     */
    @Override
    public ResponseResult list(WmMaterialDto wmMaterialDto, WmUser user) {
        //参数检查
        wmMaterialDto.checkParam();

        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN); // 未登录
        }
        //查询条件
        LambdaQueryWrapper<WmMaterial> queryWrapper = new LambdaQueryWrapper<>();
        if (wmMaterialDto.getIsCollection() != null && wmMaterialDto.getIsCollection() == 1) {
            queryWrapper.eq(WmMaterial::getIsCollection, wmMaterialDto.getIsCollection());
        }

        //查询图片列表
        //分页查询
        Page<WmMaterial> wmMaterialPage = new Page<>(wmMaterialDto.getPage(), wmMaterialDto.getSize());
        wmMaterialPage = page(wmMaterialPage, queryWrapper.eq(WmMaterial::getUserId, user.getId()).orderByDesc(WmMaterial::getCreatedTime));

        //组装分页结果
        PageResponseResult result = new PageResponseResult();
        result.setTotal((int) wmMaterialPage.getTotal());
        result.setSize((int) wmMaterialPage.getSize());
        result.setCurrentPage((int) wmMaterialPage.getCurrent());

        //返回结果
        return result.ok(wmMaterialPage.getRecords());
    }

    /**
     * 删除图片
     *
     * @param wmMaterialId
     * @param wmUser
     * @return
     */
    @Override
    @Transactional
    public ResponseResult delPicture(Integer wmMaterialId, WmUser wmUser) {
        //1.检查参数
        if (wmMaterialId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //2.查询图片是否存在
        WmMaterial wmMaterial = getById(wmMaterialId);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "图片不存在");
        }

        //3.查询该图片是否被引用
        List<WmNewsMaterial> wmNewsMaterials = wmNewsAndMaterialMapper.selectList(Wrappers.lambdaQuery(WmNewsMaterial.class).eq(WmNewsMaterial::getMaterialId, wmMaterialId));
        if (wmNewsMaterials != null && wmNewsMaterials.size() > 0) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "该图片正在使用中，不可删除");
        }

        //4.删除图片
        boolean b = removeById(wmMaterialId);
        if (!b) {
            log.error("删除图片失败,id:{}", wmMaterialId);
            throw new CustomException(AppHttpCodeEnum.SERVER_ERROR);
        }
        //4.删除minio 文件
        fileStorageService.delete(wmMaterial.getUrl());

        //5.返回结果
        return ResponseResult.okResult("删除成功");
    }

    /**
     * 收藏图片
     *
     * @param wmMaterialId
     * @param wmUser
     * @return
     */
    @Override
    public ResponseResult collect(Integer wmMaterialId, WmUser wmUser) {
        //参数检查
        if (wmMaterialId == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (wmUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //查询图片是否存在
        WmMaterial wmMaterial = getById(wmMaterialId);
        if (wmMaterial == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST, "图片不存在");
        }
        //修改图片收藏状态
        Short isCollection = wmMaterial.getIsCollection();
        isCollection = isCollection == 1 ? (short) 0 : (short) 1;
        boolean update = update(Wrappers.lambdaUpdate(WmMaterial.class).set(WmMaterial::getIsCollection, isCollection).eq(WmMaterial::getId, wmMaterialId).eq(WmMaterial::getUserId, wmUser.getId()));
        if (!update) {
            return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "图片状态修改失败");
        }
        return ResponseResult.okResult("操作成功");
    }
}
